package com.fitso.wicket.page.user;

import java.io.Serializable;

import org.apache.log4j.Logger;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.apache.wicket.validation.validator.EmailAddressValidator;
import org.apache.wicket.validation.validator.PatternValidator;

import com.fitso.model.bean.User;
import com.fitso.model.service.user.UserService;
import com.fitso.wicket.FitsoSession;
import com.fitso.wicket.page.landing.Landing;
import com.fitso.wicket.validation.PasswordValidator;

/**
 * Form that captures the user info for create a new account
 * 
 * @author timothystorm
 */
public class NewUserForm extends Form<User> implements Serializable {
	// Only change on breaking changes, i.e., removing fields
	private static final long serialVersionUID = 1L;

	private static final Logger logger = Logger.getLogger(NewUserForm.class);

	@SpringBean(name = "UserService")
	private UserService _userService;

	public NewUserForm(String id) {
		// set the User as the form model
		super(id, new CompoundPropertyModel<User>(new User()));

		// setup the fields on the page
		add(new TextField<String>("firstName").setRequired(true).add(new PatternValidator("\\w{3,}")));
		add(new TextField<String>("lastName").setRequired(true).add(new PatternValidator("\\w{3,}")));
		add(new TextField<String>("email").setRequired(true).add(EmailAddressValidator.getInstance()));
		add(new PasswordTextField("password").setRequired(true).add(PasswordValidator.getInstance()));
	}

	@Override
	protected void onSubmit() {
		logger.info("creating a new user stating...");

		User user = getModelObject();
		_userService.save(user);
		FitsoSession.get().setUser(user);
		setResponsePage(Landing.class);

		logger.info("creating a new user finished.");
	}
}
